package com.rpc.center.discover.client;

import com.rpc.common.entity.request.DiscoverDTO;
import com.rpc.common.entity.response.DiscoverRS;
import com.rpc.common.entity.HostInfoPair;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

@Setter
@Getter
public class SocketDiscoverServiceImpl implements RPCDiscoverService {
    private String address = "127.0.0.1";
    private int port = 9000;
    private DiscoverDTO discoverDTO;

    public SocketDiscoverServiceImpl(String address, int port) {
        this.address = address;
        this.port = port;
    }

    @Override
    public List<HostInfoPair> discover(DiscoverDTO discoverDTO) {
        try {
            Socket socket = new Socket(address, port);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(discoverDTO);
            outputStream.flush();
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            DiscoverRS discoverRS = (DiscoverRS) inputStream.readObject();
            outputStream.close();
            inputStream.close();
            if (discoverRS.isSuccess()) {
                for(HostInfoPair hostInfoPair:discoverRS.getServerAddressList()){
                    System.out.println(hostInfoPair.getAddress()+" "+hostInfoPair.getPort());
                }
                return discoverRS.getServerAddressList();
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
